﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Component.Utilities
{
	public static class StringUtility
	{
		public static string ConvertToString<T>(IEnumerable<T> source)
		{
			if (source == null || source.Count() <= 0)
				return "";
			StringBuilder sb = new StringBuilder();
			foreach (var item in source)
			{
				sb.Append(item).Append(',');
			}
			var result = sb.Remove(sb.Length - 1, 1).ToString();
			return result;
		}

		/// <summary>
		/// 根据ID获得文件保存路径以及文件名(不带扩展名)
		/// </summary>
		/// <param name="id"></param>
		/// <param name="fileName"></param>
		/// <returns></returns>
		public static string GetSavePath(int id, out string fileName)
		{
			string src = string.Format("{0:X8}", id);
			fileName = src.Substring(6, 2);
			return string.Format("/{0}/{1}/{2}/", src.Substring(0, 2), src.Substring(2, 2), src.Substring(4, 2));
		}

		public static string CutString(string source, int length)
		{
			if (source.Length <= length) return source;
			return source.Substring(0, length) + "...";
		}

		public static string ClearHtmlTags(string text)
		{
			return ClearHtmlTags(text,null);
		}

		public static string ClearHtmlTags(string text,int? wordNumbers)
		{
			string clearText= Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
			if (wordNumbers == null)
				return clearText;
			return clearText.Substring(0, clearText.Length - 1 > wordNumbers ? wordNumbers.Value : clearText.Length - 1);
		}

		public static string TrimStartNBSP(string text)
		{
			text = text.Trim();
			while (text.StartsWith("&nbsp") || text.StartsWith("&nbsp;"))
			{
				if (text.StartsWith("&nbsp;"))
				{
					text = text.Substring(6, text.Length - 6);
					continue;
				}
				if (text.StartsWith("&nbsp"))
					text=text.Substring(5,text.Length-5);
				
			}
			return text;
		}

	}
}
